package com.yjt.javatest.utils;

import com.yjt.javatest.entity.LoginUser;
import com.yjt.javatest.entity.User;
import com.yjt.javatest.entity.UserType;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Objects;

public class SecurityUtil {
    public static LoginUser getLoginUser() {
        LoginUser loginUser = (LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(Objects.isNull(loginUser)) {
            throw new RuntimeException("未登录");
        }
        return loginUser;
    }
    public static User getUser() {
        return getLoginUser().getUser();
    }

    public static Long getUserId() {
        return getUser().getUserId();
    }

    public static void checkUserAuthority(Long userId,String msg) {
        User user = getUser();
        if(user.getType() == UserType.ADMIN) {
            return ;
        }
        if(userId.compareTo(user.getUserId()) != 0) {
            throw new AccessDeniedException(msg);
        }
    }
    public static void checkUserAuthority(Long userId) {
        checkUserAuthority(userId, "权限不够");
    }

}

